package com.xm.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.xm.ojcodesandbox.model.ExecuteCodeRequest;
import com.xm.ojcodesandbox.model.ExecuteCodeResponse;
import com.xm.ojcodesandbox.model.ExecuteMessage;
import com.xm.ojcodesandbox.model.JudgeInfo;
import com.xm.ojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JavaNativeSandboxOld implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final Integer TIME_OUT = 5000;
    public static void main(String[] args) {
        JavaNativeSandboxOld javaNativeSandbox = new JavaNativeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        String code = ResourceUtil.readStr("testCode/SimpleCompute/Main.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);

    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        //应该是写在cmd里
//        System.setSecurityManager(new DefaultSecurityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        String userDir = System.getProperty("user.dir");

        //1 判断全局存放代码文件夹是否存在
        String globalCodePath = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if (!FileUtil.exist(globalCodePath)) {
            FileUtil.mkdir(globalCodePath);
        }
        //把用户代码隔离存放
        String userCodeParentFilePath = globalCodePath + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentFilePath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        //2 编译代码 得到class文件
        String complieCmd = String.format("javac -encoding utf-8 %s", userCodePath);
        try {
            Process process = Runtime.getRuntime().exec(complieCmd);
            new Thread( () -> {
                try {
                    Thread.sleep(TIME_OUT);
                    System.out.println("超时了");
                    process.destroy();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
            ExecuteMessage executeMessage = ProcessUtils.getExecuteMessage(process, "编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }

        //3 执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String input : inputList) {

            String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentFilePath, input);
            try {
                Process process = Runtime.getRuntime().exec(runCmd);
                ExecuteMessage executeMessage = ProcessUtils.getExecuteMessage(process, "运行");
                executeMessageList.add(executeMessage);
                System.out.println(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }
        }
        //4 整理输出
        List<String> outputList = executeMessageList.stream().map(ExecuteMessage::getMessage).collect(Collectors.toList());
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();

        long maxTime = 0;//随便取了个时间
        for (ExecuteMessage message : executeMessageList) {
            String errorMessage = message.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(message.getMessage());
            maxTime = Math.max(maxTime, message.getTime());
        }
        executeCodeResponse.setOutputList(outputList);
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        //要借助第三方库才能获取内存，process不好获取
//        judgeInfo.setMemory(0L);
        //空
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //5 清理tmpCode文件夹
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentFilePath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;

    }
}
